package com.netease.yunxin.app.im.utils

import android.os.CountDownTimer
import com.net.PolizeApi
import com.net.RetrofitManager.of
import com.net.RxCompat.schedulersTransformer
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.msg.MsgService

object ClearHelper {
    fun getLastClearTime(): Long {
        return PreferencesUtils.getLong("lastClearTime", 0)
    }

    fun setLastClearTime(timestamp: Long) {
        PreferencesUtils.putLong("lastClearTime", timestamp)
    }

    private var countDownTimer: CountDownTimer? = null
    fun clear() {
        //如果清理时间存在并且小于当前时间，则清理数据
        val lastClearTime = getLastClearTime()
        if (lastClearTime > 0 && lastClearTime < System.currentTimeMillis()) {
            NIMClient.getService(MsgService::class.java).clearMsgDatabase(true)
        }
        of(PolizeApi::class.java).getAutoClean().compose(schedulersTransformer())
            .subscribe({ ret ->
                if (ret.code == 200) {
                    ret.data.toIntOrNull()?.let {
                        val append = it * 24 * 60 * 60 * 1000 * 1000
//                            val append = 1 * 60 * 1000
                        countDownTimer = object : CountDownTimer(append.toLong(), 1000) {
                            override fun onTick(p0: Long) {
                                println(p0)
                            }

                            override fun onFinish() {
                                NIMClient.getService(MsgService::class.java)
                                    .clearMsgDatabase(true)
                                countDownTimer?.cancel()
                                countDownTimer = null
                                setLastClearTime(0)
                            }
                        }
                        countDownTimer?.start()
                        setLastClearTime(System.currentTimeMillis() + append)
                    }
                }
            }, {}, {})

    }
}